require('./db/db')

const express = require('express')
const app = express()
const { createServer } = require("node:http");
const httpServer = createServer(app);
const { Server } = require("socket.io");
const Conversation = require('./db/conversationSchema.js')
const User = require('./db/userSchema.js')
const Ai = require('./AiInterface')

//webSocket跨域访问本地后端的配置
const io = new Server(httpServer, {
    pingInterval: 30000,
    cors: {
        // origin: "http://localhost:8081"//浏览器地址栏地址
        // origin:"http://localhost:8080"//自己电脑本地测试(需打包)
        // origin:"http://192.168.0.119:8080"//线上地址测试(需打包)
        // origin:"https://7d35c3ac.r7.cpolar.cn"//线上地址测试(需打包)
        // origin: "http://192.168.0.192:8081"//H5地址栏地址
    }
})
io.on("connection", (socket) => {
    console.log('webSocket连接');
    // socket.on("disconnection", (callback) => {
    //     callback("关闭webSocket连接");
    // });
    socket.on("sendMessage", async (params, callback) => {
        await new Conversation({ state: 0, time: new Date().getTime(), ...params, admin: 'admin' }).save()
        if (!params.type) {
            await Ai({ userID: params.userID, admin: params.admin })
        }
        callback({ msg: '创建成功' })
        const data = await Conversation.find({ userID: params.userID, admin: params.admin })
        io.emit('errey', { flag: true, data, msg: '查询成功' })
    });
    socket.on("updUser", async (params, callback) => {
        console.log(params);
        const { name, admin, ...data } = params
        await User.updateMany(
            { _id: params['_id'], admin },
            { $set: data }
        )
        callback({ flag: true, msg: '修改成功' });
    });
});
httpServer.listen(3000, '0.0.0.0', () => { console.log('webSocket地址http://localhost:3000') })//浏览器webSocket请求地址
